﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Expenses.DAL.Interfaces;
using Expenses.Domain.Entities;
using NHibernate;
using NHibernate.Criterion;

namespace Expenses.DAL.Repositories
{
    public class ExpenseRepository : IExpenseRepository
    {
        public void Add(Expense expense)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            using (ITransaction transaction = session.BeginTransaction())
            {
                session.Save(expense    );
                transaction.Commit();
            }
        }

        public void Update(Expense expense)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            using (ITransaction transaction = session.BeginTransaction())
            {
                session.Update(expense);
                transaction.Commit();
            };
        }

        public void Remove(Expense expense)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            using (ITransaction transaction = session.BeginTransaction())
            {
                session.Delete(expense);
                transaction.Commit();
            }
        }

        public Expense GetById(Guid expenseId)
        {
            using (ISession session = NHibernateHelper.OpenSession())
                return session.Get<Expense>(expenseId);
        }

        public Expense GetByName(string name)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                Expense expense = session
                    .CreateCriteria(typeof(Expense))
                    .Add(Restrictions.Eq("Name", name))
                    .UniqueResult<Expense>();
                return expense;
            }
        }

        public ICollection<Expense> GetAllActive()
        {
             using (ISession session = NHibernateHelper.OpenSession())
             {
                 ICollection<Expense> expenses = session
                     .CreateCriteria(typeof (Expense))
                     //.CreateAlias("Status","s")
                     .Add(Restrictions.Eq("IsActive", true))
                     .List<Expense>();

                 return expenses;
             }
        }

        public ICollection<Expense> GetAll()
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                ICollection<Expense> expenses = session
                    .CreateCriteria(typeof(Expense))
                    //.CreateAlias("Status", "s")
                    .List<Expense>();

                return expenses;
            }
        }
    }
}
